"use strict";

const Controller = require("egg").Controller;

class HomeController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = "hi, egg";
    }

    /**
     * 登录
     */
    async login() {
        // 解析请求体，拿到用户名和密码
        const { username, password } = this.ctx.request.body;

        // 是否存在这个用户
        const user = await this.service.user.findByUsername(username);
        if (!user) {
            this.ctx.body = {
                code: 404,
                message: "该用户不存在",
            };
            return;
        }

        // 存在就校验密码
        if (user.password !== this.ctx.helper.encrypt(password)) {
            this.ctx.body = {
                code: 400,
                message: "密码错了",
            };
            return;
        }

        // 去除敏感字段
        delete user.password;

        // 生成 token
        const token = this.ctx.helper.genToken({ ...user });

        // 获取用户视图权限
        const menu = await this.service.user.getMenuListByUid(user.id);

        // 返回响应
        this.ctx.body = {
            code: 200,
            data: {
                user,
                token,
                menu,
            },
        };
    }
}

module.exports = HomeController;
